package com.example.rwq_test.designParttern.multiThread.TwoPhaseTermination.cyclicBarrierCountDownLanch;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * TODO note
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2022/11/19
 */
public class MyTask implements Runnable {
    private static final int PHASE = 5;
    private final CyclicBarrier phaseBarrier;
    private final CountDownLatch downLatch;
    private final int context;
    private static final Random RANDOM = new Random(314159);

    public MyTask(CyclicBarrier phaseBarrier, CountDownLatch downLatch, int context) {
        this.phaseBarrier = phaseBarrier;
        this.downLatch = downLatch;
        this.context = context;
    }

    public void run() {

        try {
            for (int phase = 0; phase < PHASE; phase++) {
                doPhase(phase);
                phaseBarrier.await();
            }
        } catch (InterruptedException e) {
        } catch (BrokenBarrierException e) {
        } finally {
            downLatch.countDown();
        }

    }

    private void doPhase(int phase) {
        String name = Thread.currentThread().getName();
        try {
            System.out.println(name + ":MyTask:BEGIN:context = " + context + ", phase = " + phase);
            TimeUnit.MILLISECONDS.sleep(RANDOM.nextInt(3000));
        } catch (InterruptedException e) {

        } finally {
            System.out.println(name + ":MyTask:END:context = " + context + ", phase = " + phase);
        }
    }

}
